import json

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response

from .models import ContentModel, Actor, Movie
from .serializer import ContentModelSerializer, ActorSerializer, ActorModelSerializer, MovieModelSerializer, ShowMovieSerializer
from myutils.qiniu_test import qiniu_token



class QiNiuToken(APIView):
    """
    访问此视图，返回七牛云授权token
    """
    def get(self, request):
        token = qiniu_token(bucked_name='h2002a')
        return Response({'msg': 'OK', 'code': 200, 'token': token})


class AddContentView(APIView):
    def post(self, request):
        print(request.data)
        html = request.data.get('html')
        content_data = {'content': html}
        content_serializer = ContentModelSerializer(data=content_data)
        if content_serializer.is_valid():
            content_serializer.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            return Response({'error': content_serializer.errors})

    def get(self, request):
        content_list = ContentModel.objects.all()
        content_serializer = ContentModelSerializer(content_list, many=True)
        return Response(content_serializer.data)


class AddMovieView(APIView):

    def post(self, request):
        """
        {'name': ['飞驰人生'], 'img': <xxxxxx.jpg>, 'release_date': ['2020-11-04']}
        """
        name = request.data.get('name')
        # 判断电影名重复
        movie_obj = Movie.objects.filter(name=name)
        if movie_obj:
            return Response({'msg': '该电影已存在', 'code': 400})
        movie_serializer = MovieModelSerializer(data=request.data)
        # 校验
        if movie_serializer.is_valid():
            movie_serializer.save()
            return Response({'msg': 'OK', 'code': 200})
        else:
            return Response({'error': movie_serializer.errors, 'code': 400})

    def get(self, request):
        movie_list = Movie.objects.all()
        movie_serializer = MovieModelSerializer(movie_list, many=True)
        return Response(movie_serializer.data)

class ActorView(APIView):
    """
    添加演员
    """
    def post(self, request):
        """
        添加演员，同时判断演员参演的电影有没有被添加
        """
        print(request.data)
        name = request.data.get('name')
        age = request.data.get('age')
        sex = request.data.get('sex')
        movie = request.data.get('movie_list')
        movie_list = movie.split(',')
        actor_data = {
            'name': name, 'age': age, 'sex': sex, 'movie': movie_list
        }
        actor_serializer = ActorSerializer(data=actor_data)
        if actor_serializer.is_valid():
            actor_serializer.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            return Response({'error': actor_serializer.errors, 'code': 400})

    def get(self, request):
        name = request.query_params.get('name')
        actor_obj = Actor.objects.get(name=name)
        actor_ser = ActorModelSerializer(actor_obj)
        return Response(actor_ser.data)


class ShowMovieView(APIView):

    def get(self, request):
        movie_list = list(Movie.objects.all().order_by('-release_date'))[:5]
        movie_serializer = ShowMovieSerializer(movie_list, many=True)
        return Response(movie_serializer.data)


class MovieDetailView(APIView):

    def get(self, request):
        name = request.query_params.get('name')
        movie_obj = Movie.objects.filter(name=name).first()

        if movie_obj:
            actor_list = movie_obj.actor_set.order_by('age')
            movie_ser = MovieModelSerializer(movie_obj)
            actor_ser = ActorSerializer(actor_list, many=True)
            return Response({'msg': 'OK', 'code': 200, 'movie': movie_ser.data, 'actor_list': actor_ser.data})
        else:
            return Response({'msg': '没有查到任何信息', 'code': 400})


class ShowActorView(APIView):

    def get(self, request):
        actor_list = Actor.objects.all()

        actor_ser = ActorModelSerializer(actor_list, many=True)
        actor_data = []
        print(json.dumps(actor_ser.data))
        for actor in actor_ser.data:
            actor['movie_count'] = len(actor.get('movie'))
            actor_data.append(actor)
        actor_data_new = sorted(actor_data, key=lambda x: x['movie_count'], reverse=True)
        print(actor_data_new)
        return Response(actor_data_new)


